#define SCATTERING

float4 vExtInscMultipliers;
float4 vSunColorIntensity;
float4 vBetaRayleigh;
float4 vBetaDashRayleigh;
float4 vBetaMie;
float4 vBetaDashMie;
float4 vBetaRayleighMie;
float4 vOneOverBetaRM;
float4 vHG;
float4 vConstants;
float3 vFogColor	= float3(0.51f, 0.58f, 0.66f);
float2 FogStartEnd	= float2(0.0f, 2000.0);

float4 Scattering(float3 vPos, float3 vEyePos, float3 vLightDir, float4 color)
{
	float3 vEyeVert = vEyePos - vPos; 
	float dist = length(vEyeVert.xyz);
	vEyeVert = normalize(vEyeVert);
	float cosTheta = max(0, dot(vLightDir.xyz, vEyeVert.xyz));
	float Phase1theta = cosTheta * cosTheta + 1.0f;
	float3 extinction = - vBetaRayleighMie.xyz * dist * vConstants.y;
	extinction	=	exp(-extinction);	 
	float4 r4;
	r4.x = vHG.z * cosTheta + vHG.y;
	r4.x = rsqrt(r4.x);						
	r4.y = r4.x * r4.x;			
	r4.x = r4.y * r4.x;
	float Phase2theta = r4.x * vHG.x;
	float3	rayleigh = vBetaDashRayleigh *Phase1theta; 
	float3	mie	= vBetaDashMie * Phase2theta;
	float3	temp = vConstants.x	- extinction;
	float3	inscatter	= mie + rayleigh;	
	inscatter*=temp;
	inscatter *= vOneOverBetaRM;
	inscatter *= vExtInscMultipliers.y;
	inscatter *= vSunColorIntensity.xyz * vSunColorIntensity.w;
	extinction.xyz *= vSunColorIntensity.xyz * vSunColorIntensity.w;	
	float4 res = color;
	float fog = (FogStartEnd.y * 2 - dist)/(FogStartEnd.y * 2 - FogStartEnd.x);
	fog = min(fog, 1);
	res.rgb = lerp(vFogColor.xyz, res.rgb, fog);
	res.rgb *= saturate(extinction.xyz);
	res.rgb += clamp(-inscatter.xyz, 0.0f, 0.25f);	
	res.rgb = saturate(res.rgb);
	return res;
}
